from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.decorators import  api_view,permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.db import connection, transaction, IntegrityError
from django.shortcuts import get_object_or_404
import json,os,uuid
from goods.models import Good
from django.core.paginator import Paginator
from mid_project import settings

@api_view(['GET'])
@permission_classes([AllowAny]) 
def product_list(request):
    # 获取商品列表
    # 搜索相关参数
    page = int(request.GET.get('page', 1))
    search = request.GET.get('search')
    category = request.GET.get('category')
    uid = request.GET.get('uid')

    goods = Good.objects.select_related('uid').all()
    #过滤
    
    if search:
        goods = goods.filter(title__icontains=search)  # 根据标题搜索
    if category:
        goods = goods.filter(category=category)  # 根据分类过滤 (根本没做种类标记字段)

    if uid:
        goods = goods.filter(uid_id=uid)  # 根据用户ID过滤，如果是个人页面，售出商品也显示
    else:
        goods = goods.filter(status=1)  # 只显示状态为1（在售）的商品

    # 分页处理
    paginator = Paginator(goods, 50)  # 每页50条记录
    page_obj = paginator.get_page(page)
    
    results=[]
    for obj in page_obj:
        results.append({
            "gid": obj.Gid,
            "title": obj.title,
            "description": obj.description,
            "price": str(obj.price),
            "images": obj.images,
            "uid": obj.uid_id,
            "seller_username": obj.uid.username,
            "status": obj.status,
            "view_count": obj.view_count
        })

    # 构建分页信息
    current_page = page_obj.number
    total_pages = paginator.num_pages
    
    # 计算总数
    num_of_goods = paginator.count

    response = {
        "count": num_of_goods,
        "total_pages": total_pages,
        "results": results
    }
    return JsonResponse(response, status=200)


@api_view(['GET'])
@permission_classes([AllowAny]) 
def product_detail(request, id):
    # 获取商品详情
    print('PRODUCT DETAIL request:', request.method, request.path, request.GET,request.data)

    good = Good.objects.get(pk=id)
    # 增加浏览量计数
    good.view_count += 1
    good.save(update_fields=['view_count'])
    
    response = {
        "gid": good.Gid,
        "title": good.title,
        "description": good.description,
        "price": str(good.price),
        "images": good.images,
        "uid": good.uid_id,
        "seller_username": good.uid.username,
        "status": good.status,
        "view_count": good.view_count
    }

    return JsonResponse(response, status=200)


@api_view(['POST'])
@permission_classes([IsAuthenticated]) 
def product_create(request):
    # 创建商品
    print('CREATE PRODUCT request:', request.method, request.path, request.data)

    data = request.data
    title = data.get('title')
    description = data.get('description', '')
    price = data.get('price')

    uid = request.user.id
    status = 1

    # 简单必填检查
    if not title or not price or not uid:
        return JsonResponse({'error': '缺少必要字段'}, status=400)

    try:
        # 图片处理
        images = request.FILES.getlist('images')
        images_paths = []
        for image in images:
            #uuid文件名
            #ext获取扩展名  eg: .jpg .png
            ext = os.path.splitext(image.name)[1]
            unique_filename = f"{uuid.uuid4().hex}{ext}"
            #存储路径/media/images/picture/{unique_filename}
            save_directory = os.path.join(settings.MEDIA_ROOT, 'images','picture')
            full_file_path = os.path.join(save_directory, unique_filename)

            #存储
            save_path = default_storage.save(full_file_path, image)
            images_paths.append(save_path)

        # 创建商品
        good = Good.objects.create(
            title=title,
            description=description,
            price=price,
            images=images_paths,
            uid_id=uid,
            status=status,
            view_count=0
        )
    except Exception as e:
        return JsonResponse({'error': '商品创建失败',"message":e}, status=500)
    
    response = {
        "gid": good.Gid,
        "name": good.title,
        "description": good.description,
        "price": str(good.price),
        "images": good.images,
        "uid": good.uid_id,
        "status": good.status,
        "view_count": good.view_count
    }
    # 返回结果
    return JsonResponse(response, status=201)


@api_view(['PUT'])
@permission_classes([IsAuthenticated]) 
def product_update(request, id):
    # 更新商品
    print('UPDATE PRODUCT request:', request.method, request.path, request.data)

    
    good = Good.objects.get(pk=id)

    good.title = request.data.get('title', good.title)
    good.description = request.data.get('description', good.description)
    good.price = request.data.get('price', good.price)
    good.status = request.data.get('status', good.status)

    # 删除原有图片文件
    for image_path in good.images:
            if default_storage.exists(image_path):
                default_storage.delete(image_path)
    print('商品原有图片',good.images)
    print('1')
    try:
        # 图片处理 - 保持原有图片顺序
        images = request.FILES.getlist('images')
        print('UPDATE PRODUCT images:', images)

        images_paths = []
        for image in images:
            #uuid文件名
            #ext获取扩展名  eg: .jpg .png
            ext = os.path.splitext(image.name)[1]
            unique_filename = f"{uuid.uuid4().hex}{ext}"
            #存储路径/media/images/picture/{unique_filename}
            save_directory = os.path.join(settings.MEDIA_ROOT, 'images','picture')
            full_file_path = os.path.join(save_directory, unique_filename)

            #存储   
            save_path = default_storage.save(full_file_path, image)
            images_paths.append(save_path)
        good.images = images_paths
        good.save()
        
        print('商品图片',good.images)
    except Exception as e:
        return JsonResponse({'error': '商品修改失败',"message":e}, status=500)
    
    response = {
        "gid": good.Gid,
        "title": good.title,
        "description": good.description,
        "price": str(good.price),
        "images": good.images,
        "uid": good.uid_id,
        "status": good.status,
        "view_count": good.view_count
    }

    return JsonResponse(response, status=200)


@api_view(['DELETE'])
@permission_classes([IsAuthenticated]) 
def product_delete(request, id):
    # 删除商品
    print('DELETE PRODUCT request:', request.method, request.path)
    good = Good.objects.get(pk=id)

    try:
        #删关联图片
        images_paths = good.images
        for image_path in images_paths:
            if default_storage.exists(image_path):
                default_storage.delete(image_path)

        good.delete()
    except Exception as e:
        return JsonResponse({'error': '商品删除失败',"message":e}, status=500)
    
    return JsonResponse({"message": "商品删除成功"}, status=200)
